<?php


namespace app\api\controller\v16;


use app\api\controller\v13\Auth2;
use app\common\cachemodel\Article;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\ArticleCommentGood;
use app\common\cachemodel\ArticleCommentReply;
use app\common\cachemodel\ArticleRead;
use app\common\cachemodel\GoddessArea as GoddessAreaModel;
use app\common\cachemodel\GoddessBaseInfo;
use app\common\cachemodel\ZlGoddessState;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\ConfigManage;
use app\common\lib\Util;
use app\common\model\ArticleCategory;
use app\common\model\ArticleCollect;
use app\common\model\ArticleGood;
use app\common\model\User;
use think\response\Json;

/**
 * 文章详情与评论列表
 * @version 2.0.0
 * Class ArticleCommentGet
 * @package app\api\controller\v16
 */
class ArticleCommentGet extends Auth2
{
    /**
     * 文章信息和评论列表
     * @return Json
     * @throws \Exception
     */
    public function articleInfoAndCommentList()
    {
        $page = input('page/d', 1);
        $id = input('id/d', 0);
        $type = input('type/d', 0);
        $uid = $this->user ? (int)$this->user['id'] : null;
        if (!$id || !in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常');
        }
        $resData = [];
        if ($page === 1)
        {
            if ($uid)
            {   // 获取用户点赞话题ids
                $goodIds = (new ArticleGood())->getGoodFromCache($uid, $type);
                // 获取用户收藏话题ids
                $collectIds = array_keys((new ArticleCollect())->getUserAllCollectFromCache($uid, $type));
            } else
            {
                $goodIds = [];
                $collectIds = [];
            }
            $configModel = new ConfigManage();
            switch ($type)
            {
                case 1:
                    $articleInfo = current((new Article())->batchGetInfo([$id], ['id', 'cids', 'read', 'read_base', 'thumb', 'title', 'publish_time', 'author', 'avatar', 'content', 'introduction', 'comment', 'good', 'collect', 'a_id']));
                    if (!$articleInfo)
                    {
                        return show(config('code.error'), '星文不存在');
                    }
                    $cids = explode(',', $articleInfo['cids']);
                    $category = (new ArticleCategory())->getArticleCategory();
                    $category = array_column($category, null, 'id');
                    $categoryName = [];
                    foreach ($cids as $cid)
                    {
                        if (!empty($category[$cid]))
                        {
                            $categoryName[] = $category[$cid];
                        }
                    }
                    // 点赞数量计算
                    $goodNum = (int)(($articleInfo['good'] ?? 0) + floor(((($articleInfo['read'] ?? 0) + ($articleInfo['read_base'] ?? 0)) / 30)));
                    $resData['article_info'] = [
                        'id' => $id,
                        'type' => 1,
                        'url' => null,
                        'thumb' => $articleInfo['thumb'] ?? '',
                        'title' => $articleInfo['title'] ?? '',
                        'time' => Util::timeToStr($articleInfo['publish_time']),
                        'author' => $articleInfo['author'] ?? '',
                        'avatar' => $articleInfo['avatar'] ?? '',
                        'content' => htmlspecialchars_decode($articleInfo['content'] ?? ''),
                        'introduction' => $articleInfo['introduction'] ?? '',
                        'comment_num' => ($articleInfo['comment'] ?? 0) < 0 ? 0 : (int)($articleInfo['comment'] ?? 0),
                        'good_num' => $goodNum < 0 ? 0 : $goodNum,
                        'collect_num' => ($articleInfo['collect'] ?? 0) < 0 ? 0 : (int)($articleInfo['collect'] ?? 0),
                        'duration' => null,
                        'is_good' => in_array($id, $goodIds) ? 1 : 0,
                        'is_collect' => in_array($id, $collectIds) ? 1 : 0,
                        'user_type' => $configModel->innerUser((int)($articleInfo['a_id'] ?? 0)),
                        'release_time' => date('Y-m-d H:i:s', $articleInfo['publish_time']),
                        'content_category' => $categoryName ? implode('、', array_column($categoryName, 'name')) : ''
                    ];

                    $resData['theme_info'] = null;
                    break;
                case 2:
                    $goddessState = (new ZlGoddessState())->getInfoById($id, ['type', 'url', 'thumb', 'title', 'publish_time', 'author', 'avatar', 'content', 'introduction', 'comment_num', 'good_num', 'collect_num', 'duration', 'read_num', 'read_base', 'a_id']);
                    if (!$goddessState)
                    {
                        return show(config('code.error'), '动态不存在');
                    }
                    $goodNum = (int)(($goddessState['good_num'] ?? 0) + floor(((($goddessState['read_num'] ?? 0) + ($goddessState['read_base'] ?? 0)) / 30)));
                    $resData['article_info'] = [
                        'id' => $id,
                        'type' => (int)($goddessState['type'] ?? 0),
                        'url' => $goddessState['url'] ?? '',
                        'thumb' => $goddessState['thumb'] ?? '',
                        'title' => $goddessState['title'] ?? '',
                        'time' => Util::timeToStr($goddessState['publish_time']) ?? '',
                        'author' => $goddessState['author'] ?? '',
                        'avatar' => $goddessState['avatar'] ?? '',
                        'content' => htmlspecialchars_decode($goddessState['content'] ?? ''),
                        'introduction' => $goddessState['introduction'] ?? '',
                        'comment_num' => ($goddessState['comment_num'] ?? 0) < 0 ? 0 : (int)($goddessState['comment_num'] ?? 0),
                        'good_num' => $goodNum < 0 ? 0 : $goodNum,
                        'collect_num' => ($goddessState['collect_num'] ?? 0) < 0 ? 0 : (int)($goddessState['collect_num'] ?? 0),
                        'duration' => (int)($goddessState['duration'] ?? 0),
                        'is_good' => in_array($id, $goodIds) ? 1 : 0,
                        'is_collect' => in_array($id, $collectIds) ? 1 : 0,
                        'user_type' => $configModel->innerUser((int)($goddessState['a_id'] ?? 0)),
                        'release_time' => date('Y-m-d H:i:s', $goddessState['publish_time']),
                        'content_category' => '女神动态'
                    ];
                    $resData['theme_info'] = null;
                    break;
                case 3:
                    // 获取话题信息
                    $themeInfo = current((new GoddessAreaModel())->batchGetThemeInfo($id, ['publish_time', 'title', 'comment_num', 'good_num', 'collect_num', 'read_num', 'read_base', 'a_id', 'author', 'avatar']));
                    if (!$themeInfo)
                    {
                        return show(config('code.error'), '互动不存在');
                    }
                    // 点赞数量计算
                    $goodNum = (int)(($themeInfo['good_num'] ?? 0) + floor(((($themeInfo['read_num'] ?? 0) + ($themeInfo['read_base'] ?? 0)) / 30)));
                    // 话题信息
                    $resData['article_info'] = null;
                    $resData['theme_info'] = [
                        'id' => $id,
                        'avatar' => $themeInfo['avatar'] ?? '',
                        'nickname' => $themeInfo['author'] ?? '',
                        'time' => Util::timeToStr($themeInfo['publish_time']),
                        'content' => htmlspecialchars_decode($themeInfo['title'] ?? ''),
                        'comment_num' => (int)($themeInfo['comment_num'] ?? 0),
                        'good_num' => $goodNum < 0 ? 0 : $goodNum,
                        'collect_num' => ($themeInfo['collect_num'] ?? 0) < 0 ? 0 : (int)($themeInfo['collect_num'] ?? 0),
                        'is_good' => in_array($id, $goodIds) ? 1 : 0,
                        'is_collect' => in_array($id, $collectIds) ? 1 : 0,
                        'user_type' => $configModel->innerUser((int)($themeInfo['a_id'] ?? 0)),
                        'release_time' => date('Y-m-d H:i:s', $themeInfo['publish_time']),
                    ];
                    break;
                default :
                    return show(config('code.error'), '内容不存在');
                    break;
            }
        }
        if ($uid)
        {
            //内容已读
            (new ArticleRead())->saveData($uid, $type, $id);
        }
        // 获取用户评论列表信息
        $data = (new ArticleComment())->getPageCommentList($uid, $type, $id, 2, $page);
        $resData = array_merge($resData, $data);
        return show(config('code.success'), '请求成功', $resData);
    }

    // /**
    //  * 评论详情
    //  */
    // public function commentList()
    // {
    //     $aid = input('param.aid/d');
    //     $page = input('param.page/d', 1);
    //     $uid = $this->user ? (int)$this->user['id'] : null;
    //
    //     $data = (new ArticleComment())->getPageCommentList($uid, 1, $aid, 2, $page);
    //
    //     return show(config('code.success'), '请求成功', $data);
    // }

    /**
     * 评论详情和回复列表
     */
    public function commentReplyList()
    {
        $commentId = input('comment_id/d', 0);
        $page = input('page/d', 1);
        $uid = $this->user ? (int)$this->user['id'] : null;
        if (!$commentId)
        {
            return show(config('code.error'), '请求异常');
        }

        $resData = [];
        if ($page === 1)
        {
            // 评论详情
            $commentInfo = current((new ArticleComment())->batchGetInfo([$commentId], ['create_time', 'uid', 'goods', 'reply', 'content']));
            if (!$commentInfo)
            {
                return show(config('code.error'), '数据不存在');
            }
            //获取内部官方用户
            $appUser = (new ConfigManage())->innerUser((int)($commentInfo['uid'] ?? 0));
            // 获取用户所有的评论点赞ID
            $goods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 1) : [];
            $isOwner = $commentInfo['uid'] == $uid ? 1 : 0; // 判断是否是本人
            // 获取用户信息
            $userInfo = $isOwner ? $this->user : current((new User())->batchGetUserInfo([$commentInfo['uid']], ['nickname']));
            // 评论的点赞数量转换成int
            $commentInfo['goods'] = (int)$commentInfo['goods'];
            $resData['comment_info'] = [
                'id' => $commentId,
                'avatar' => $userInfo['avatar'] ?? '',
                'nickname' => $userInfo['nickname'] ?? '匿名用户',
                'time' => Util::timeToStr($commentInfo['create_time']),
                'content' => htmlspecialchars_decode($commentInfo['content']),
                'reply_num' => (int)$commentInfo['reply'],
                'good_num' => $commentInfo['goods'] < 0 ? 0 : $commentInfo['goods'],
                'is_good' => in_array($commentId, $goods) ? 1 : 0,
                'vip' => (new ZlUserVip())->getUserVipLevel($commentInfo['uid']),
                'is_owner' => $isOwner,
                'user_type' => $appUser,
            ];
        } else
        {
            $resData['comment_info'] = null;
        }

        $pageData = (new ArticleCommentReply())->getPageCommentReplyList($uid, $commentId, 2, $page);

        $resData = array_merge($resData, $pageData);
        return show(config('code.success'), '请求成功', $resData);
    }
}
